﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Dynamic;
using Microsoft.AspNetCore.SignalR;
using XinLife.Common.SignalR;

namespace XinLife.Common.Filters
{
    /// <summary>
    /// 全局捕获程序运行异常信息
    /// </summary>
    public class ExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        private readonly ILogger<ExceptionHandlingAttribute> _logger;
        private readonly IHubContext<ChatHub> _hubContext;
        public ExceptionHandlingAttribute(ILogger<ExceptionHandlingAttribute> logger, IHubContext<ChatHub> hubContext)
        {
            _logger = logger;
            _hubContext = hubContext;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            dynamic json = new ExpandoObject();
            json.code = 500;
            json.msg = context.Exception.Message;//错误信息
            context.Result = new InternalServerErrorObjectResult(json);

            var exception = context.Exception;
            string requestPath = context.HttpContext.Request.Path.ToString();
            string queryString = context.HttpContext.Request.QueryString.ToString();
            var type = System.Reflection.MethodBase.GetCurrentMethod()?.DeclaringType;
            string exDesc = requestPath + queryString;
            //采用log 进行错误日志记录
            string erro_msg = $"请求：{exDesc}\r\n异常类型：{exception.GetType().Name} \r\n异常信息：{exception.Message} \r\n【堆栈调用】：\r\n{exception.StackTrace}"; ;

             _hubContext.Clients.All.SendAsync("ErroMsg", erro_msg);
            _logger.LogError(erro_msg);
        }
        public class InternalServerErrorObjectResult : ObjectResult
        {
            public InternalServerErrorObjectResult(object value) : base(value)
            {
                StatusCode = StatusCodes.Status500InternalServerError;
            }
        }
    }
}
